package com.frinder.hadoop.hbase.original;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.hadoop.hbase.client.Connection;

/**
 * @author frinder
 * @date 2018/6/30
 * @Description: 获取 & 归还 连接实现
 */
@Slf4j
public class MyConnectionProvider implements ConnectionProvider {

    private static GenericObjectPool<Connection> pool;

    static {
        HBasePooledObjectFactory factory = new HBasePooledObjectFactory();
        try {
            pool = new GenericObjectPool<>(factory);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    @Override
    public Connection getConn() {
        try {
            log.info("*** 从连接池获取连接！");
            return pool.borrowObject();
        } catch (Exception e) {
            throw new RuntimeException("getConn 失败，请检查配置", e);
        }
    }

    @Override
    public void returnConn(Connection conn) {
        try {
            if (null != conn) {
                log.info("*** 归还连接池连接！");
                pool.returnObject(conn);
            }
        } catch (Exception e) {
            throw new RuntimeException("returnConn 失败，请检查配置", e);
        }
    }
}
